import { defineStore } from 'pinia';
import { 
  getFunctionList, 
  createFunction as apiCreateFunction, 
  updateFunction as apiUpdateFunction, 
  deleteFunction as apiDeleteFunction,
} from '@/apis/function';
import type { AiFunctionDTO } from '@/apis/function';

// 前端使用的函数对象接口，尽量与后端保持一致
export interface CustomFunction {
  id: string;
  name: string;
  description: string;
  type: string;
  parameters: string;
  needConfirm: boolean;
  triggerFrontend: boolean;
  frontendAction?: string | null;
  regenerateResult: boolean;
  implementationClass: string;
  implementationMethod: string;
  status: 'active' | 'inactive';
}

export const useFunctionsStore = defineStore('functions', {
  state: () => ({
    functions: [] as CustomFunction[],
  }),
  
  actions: {
    async fetchFunctions(): Promise<CustomFunction[]> {
      try {
        const response = await getFunctionList({ page: 1, size: 100 });
        if (response.code === 200 && response.data) {
          // 后端 VO 转为前端使用的格式
          this.functions = response.data.records.map(item => ({
            ...item,
            // 唯一需要转换的字段：status从数字转为字符串
            status: item.status === 1 ? 'active' : 'inactive'
          }));
        }
        return this.functions;
      } catch (error) {
        console.error('获取函数列表失败:', error);
        return [];
      }
    },
    
    async createFunction(func: Omit<CustomFunction, 'id'>): Promise<boolean> {
      try {
        // 前端数据转换为后端DTO格式
        const apiData: AiFunctionDTO = {
          name: func.name,
          description: func.description,
          type: func.type || 'general',
          parameters: func.parameters,
          needConfirm: func.needConfirm,
          triggerFrontend: func.triggerFrontend,
          frontendAction: func.triggerFrontend ? (func.frontendAction || 'default') : null,
          regenerateResult: func.regenerateResult,
          implementationClass: func.implementationClass || 'com.government.ai.biz.AiFunctionImplementation',
          implementationMethod: func.implementationMethod || func.name,
          status: func.status === 'active' ? 1 : 0
        };
        
        console.log('创建函数请求数据:', apiData);
        
        const response = await apiCreateFunction(apiData);
        console.log('创建函数响应:', response);
        
        if (response.code === 200) {
          return response.data;
        }
        throw new Error('创建函数失败');
      } catch (error) {
        console.error('创建函数失败:', error);
        throw error;
      }
    },
    
    async updateFunction(func: CustomFunction): Promise<boolean> {
      try {
        // 前端数据转换为后端DTO格式
        const apiData: AiFunctionDTO = {
          id: func.id,
          name: func.name,
          description: func.description,
          type: func.type,
          parameters: func.parameters,
          needConfirm: func.needConfirm,
          triggerFrontend: func.triggerFrontend,
          frontendAction: func.triggerFrontend ? (func.frontendAction || 'default') : null,
          regenerateResult: func.regenerateResult,
          implementationClass: func.implementationClass,
          implementationMethod: func.implementationMethod,
          status: func.status === 'active' ? 1 : 0
        };
        
        console.log('更新函数请求数据:', apiData);
        
        const response = await apiUpdateFunction(apiData);
        console.log('更新函数响应:', response);
        
        if (response.code === 200) {
          return response.data;
        }
        throw new Error('更新函数失败');
      } catch (error) {
        console.error('更新函数失败:', error);
        throw error;
      }
    },
    
    async deleteFunction(id: string): Promise<void> {
      try {
        const response = await apiDeleteFunction(id);
        if (response.code === 200) {
          // 删除成功，更新本地状态
          this.functions = this.functions.filter(f => f.id !== id);
        } else {
          throw new Error('删除函数失败');
        }
      } catch (error) {
        console.error('删除函数失败:', error);
        throw error;
      }
    }
  }
}); 